package com.bw.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.home.intent.LoginIntent
import com.bw.home.service.LoginService
import com.bw.home.state.LoginState
import com.bw.lib_mvi.viewmodel.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class LoginViewModel : BaseViewModel<LoginIntent>() {
    private val service: LoginService by lazy { LoginService() }
    private val _state = MutableStateFlow<LoginState>(LoginState.init)

    val state: StateFlow<LoginState>
        get() = _state

    override fun handlerIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {

                    is LoginIntent.login -> {
                        doLogin(it)
                    }

                    is LoginIntent.register -> {
                        doRegister(it)
                    }

                    else -> {}
                }
            }
        }
    }

    //注册
    private fun doRegister(it: LoginIntent.register) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.register(it.username, it.password)
            if (data.code == 0) {
                _state.value = LoginState.register(data.data)
            } else {
                _state.value = LoginState.Failed
            }
        }
    }

    //登录
    private fun doLogin(it: LoginIntent.login) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.login(it.username, it.password)
            if (data.code == 0) {
                _state.value = LoginState.login(data.data)
            } else {
                _state.value = LoginState.Failed
            }
        }
    }
}